<template>
  <div>
    <el-dialog
      title="获取序列号"
      width="1260px"
      :visible.sync="dialogTableVisible"
      v-dialogDrag
      :close-on-click-modal="false"
      customClass="mes_dialog"
      @closed="closeDialog">
      <div class="table_container">
        <el-table
          :data="[formData]"
          border
          class="table_dialog">
          <el-table-column
            align="center"
            prop="turnoverNumber"
            label="周转码"
            min-width="240"
            show-overflow-tooltip>
          </el-table-column>
          <el-table-column
            align="center"
            prop="materialNumber"
            label="物料编码"
            show-overflow-tooltip>
          </el-table-column>
          <el-table-column
            align="center"
            prop="materialName"
            label="物料名称"
            show-overflow-tooltip>
          </el-table-column>
          <el-table-column
            align="center"
            prop="drawingNumber"
            label="图号"
            width="140"
            show-overflow-tooltip>
          </el-table-column>
          <el-table-column
            align="center"
            prop="productBatchNumber"
            label="批次号"
            show-overflow-tooltip>
          </el-table-column>
          <el-table-column
            align="center"
            prop="carveNumber"
            label="可刻字总数量"
            show-overflow-tooltip>
          </el-table-column>
          <el-table-column
            align="center"
            :resizable="false"
            prop="productionQuantity"
            label="计划数量">
          </el-table-column>
        </el-table>
      </div>
      <el-form class="params_panel mes_btn"
               ref="listForm"
               @submit.native.prevent
               :model="serialData"
               :rules="rules"
               v-if="formData.turnoverId  && formData.workstageProcessStatusValue !== 'Finished'">
        <div class="input_panel">
          <span>前缀</span>
          <el-form-item prop="prefix">
            <el-input :disabled="serialMaxNum <= 0" v-model="serialData.prefix" placeholder="只能包含字母和数字"></el-input>
          </el-form-item>
        </div>
        <span class="link_panel">
          <i class="iconfont icon-btn_addnew"></i>
        </span>
        <div class="input_panel">
          <span>数量</span>
          <el-form-item prop="num">
            <el-input
              :disabled="serialMaxNum <= 0"
              v-model="serialData.num"
              type="number"
              min="1"
              :placeholder="`不能大于${serialMaxNum}`">
            </el-input>
          </el-form-item>
        </div>
        <span class="link_panel">
          <i class="iconfont icon-btn_addnew"></i>
        </span>
        <div class="input_panel">
          <span>位数</span>
          <el-form-item prop="digit">
            <el-input
              :disabled="serialMaxNum <= 0"
              v-model="serialData.digit"
              v-positive-int="{'min':1, 'max':9}"
              type="number"
              placeholder="不能大于9">
            </el-input>
          </el-form-item>
        </div>
        <el-button type="primary" class="btn_panel" @click="getSerialNumber" :disabled="serialMaxNum <= 0">生成序列号</el-button>
      </el-form>
      <div class="serial_number_list" v-if="formData.workstageProcessStatusValue !== 'Finished'">
        <old-serial-number :workStageMsg="workStageMsg" ref="OldSerialNumber" @historyHandle="historyHandle" @getCount="getCount" @deleteSerialNumber="deleteSerialNumber"></old-serial-number>
        <new-serial-number ref="NewSerialNumber" @newHandle="newHandle"></new-serial-number>
      </div>
      <div class="serial_number_list" v-if="formData.workstageProcessStatusValue === 'Finished'">
        <history-serial-number ref="HistorySerialNumber" :workStageMsg="workStageMsg"></history-serial-number>
      </div>
      <span slot="footer" class="dialog-footer mes_btn">
        <el-button
          :disabled="serialMaxNum <= 0"
          type="primary"
          @click="saveSerialNumber"
          v-if="formData.workstageProcessStatusValue !== 'Finished'">
          提交
        </el-button>
        <el-button @click="dialogTableVisible = false">取消</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import {isContainNumOrLetter} from '@/utils/validate'
import {isOverLength, isPosInteger, maxFigure} from './formValidate'
import {OldSerialNumber, NewSerialNumber, HistorySerialNumber} from './serialNumber'
export default {
  name: 'GetSerialNumber',
  components: {
    OldSerialNumber,
    NewSerialNumber,
    HistorySerialNumber
  },
  data() {
    return {
      dialogTableVisible: false,
      formData: [], // 工序数据
      // 获取序列号请求参数
      serialData: {
        prefix: '',
        num: null
      },
      serialNumberList: [], // 生产序列号列表
      serialNumberHistoryList: [], // 生产序列号历史列表
      currentPrefix: '', // 当前序列号前缀
      workStageMsg: {}, // 当前工序基础数据
      serialCount: 0, // 已刻字数量
      serialMaxNum: 0, // 工序号最大生产数量
      rules: {
        prefix: [
          {required: true, message: '请输入前缀', trigger: 'blur'},
          {validator: isContainNumOrLetter, message: '前缀只能包含字母和数字', trigger: 'change'},
          {validator: isOverLength, message: '前缀长度不能大于20', trigger: 'change'}
        ],
        num: [
          {required: true, message: '请输入数量', trigger: 'blur'},
          {validator: isPosInteger, message: '数量必须是正整数', trigger: 'change'},
          {validator: this.isGeaterThan, message: `不能大于限定值`, trigger: 'change'}
        ],
        digit: [
          {required: true, message: '请输入位数', trigger: 'blur'},
          {validator: isPosInteger, message: '数量必须是正整数', trigger: 'change'},
          {validator: maxFigure, message: '不能大于9', trigger: 'change'}
        ]
      },
      saveStatus: true, // 按钮是否可以提交状态
    }
  },
  methods: {
    /**
     * 打开弹窗
     * @param id 工单id
     */
    openDialog(list) {
      this.formData = list[0]
      this.workStageMsg.turnoverId = this.formData.turnoverId
      this.workStageMsg.number = this.formData.materialNumber
      this.workStageMsg.workorderId = this.formData.workorderId
      this.dialogTableVisible = true
      this.calcCarveNumber()
      this.$nextTick(() => {
        if (this.formData.workstageProcessStatusValue === 'Finished') {
          this.$refs.HistorySerialNumber.getHistorySerialNumber()
        } else {
          this.getMaxNum()
          this.$refs.OldSerialNumber.getHistorySerialNumber()
        }
      })
    },
    // 计算可刻字数量(carveNumber)
    calcCarveNumber() {
      if (this.formData.workstageProcessStatusValue === 'Finished') {
        this.formData.carveNumber = this.formData.inputQuantity
      } else {
        this.formData.carveNumber = this.formData.inputQuantity || this.formData.productionQuantity - this.formData.scrapQuantity
      }
    },
    // 获取历史回调
    historyHandle(prefix) {
      this.$set(this.serialData, 'prefix', prefix)
    },
    // 获取新建序列号回调
    newHandle(result) {
      let obj = JSON.parse(JSON.stringify(result))
      this.serialNumberList = obj.serialNumberList
      this.currentPrefix = obj.prefix
    },
    // 序列号最大获取数量
    getMaxNum() {
      this.$store.dispatch('saveData', {
        method: 'post',
        url: 'a/turnovermaterialserialnumber/turnoverMaterialSerialNumber/getMaxSerialNumCount',
        data: {
          turnoverWorkstageId: this.formData.id,
          turnoverId: this.formData.turnoverId,
          workorderId: this.formData.workorderId,
        },
        noCommit: true
      }).then((res) => {
        res.data >= 0 ? this.serialMaxNum = res.data : this.serialMaxNum = this.formData.carveNumber - this.serialCount
        this.rules.num[2].message = `不能大于${this.serialMaxNum}`
      }).catch(() => {
        this.serialMaxNum = this.formData.carveNumber - this.serialCount
      })
    },
    // 获取已刻字数量
    getCount(count) {
      this.serialCount = count
    },
    // 数量是否大于剩余刻字数量
    isGeaterThan(rule, num, callback) {
      if (num > this.serialMaxNum) {
        callback(new Error(rule.message))
      } else {
        callback()
      }
    },
    // 删除序列号
    deleteSerialNumber() {
      this.getMaxNum()
    },
    /**
     * 获取序列号
     * @param id 工单id
     */
    getSerialNumber() {
      this.serialData.num = Number(this.serialData.num)
      this.serialData.digit = Number(this.serialData.digit)
      this.serialData.workorderId = this.formData.workorderId
      this.$refs['listForm'].validate((valid) => {
        if (valid) {
          let data = Object.assign(this.serialData, {turnoverWorkstageId: this.formData.id, turnoverId: this.formData.turnoverId})
          this.$refs.NewSerialNumber.getSerialNumber(JSON.parse(JSON.stringify(data)))
        }
      })
    },
    /**
     * 保存序列号
     * @param id 工单id
     */
    saveSerialNumber() {
      if (!this.serialNumberList.length) {
        return this.tipMessage('error', '请生成序列号')
      }
      if (!this.saveStatus) return
      this.saveStatus = false
      let saveData = this.serialNumberList.map((item) => {
        return Object.assign(
          {
            prefix: this.currentPrefix,
            serialNumber: item,
            batchNumber: this.formData.productBatchNumber,
            used: 'ID_BT_False'
          }, this.workStageMsg)
      })
      this.$store.dispatch('saveData', {
        method: 'post',
        url: 'a/turnovermaterialserialnumber/turnoverMaterialSerialNumber/saveBatch',
        data: {turnoverMaterialSerialNumberList: saveData},
        noCommit: true
      }).then(() => {
        this.tipMessage('success', '保存序列号成功')
        this.dialogTableVisible = false
        this.$emit('submitSuccess')
      }).catch(() => {
        this.saveStatus = true
      })
    },
    // 关闭弹窗、重置数据
    closeDialog() {
      if (this.formData.workstageProcessStatusValue === 'Finished') {
        this.$refs.HistorySerialNumber.isLoading = false
        this.$refs.HistorySerialNumber.serialNumberList = []
      } else {
        this.$refs.NewSerialNumber.isLoading = false
        this.$refs.NewSerialNumber.serialNumberList = []
        this.$refs.OldSerialNumber.isLoading = false
        this.$refs.OldSerialNumber.turnoverSerialNumbers = []
        this.$refs.OldSerialNumber.workorderSerialNumbers = []
        this.$refs.OldSerialNumber.activeIndex = 1
      }
      this.formData = {}
      this.serialData = {}
      this.serialNumberList = []
      this.serialNumberHistoryList = []
      this.saveStatus = true
    },
    /**
     * 提示
     * @param str 提示内容
     */
    tipMessage(type, str) {
      this.$message({
        type: type,
        message: str,
        duration: 1500,
        center: true
      })
    }
  }
}
</script>

<style lang="less">
  .params_panel{
    display: flex;
    align-items: center;
    justify-content: center;
    padding-top: 40px;
    .input_panel{
      width: 180px;
      height: 44px;
      position: relative;
      margin-right: 20px;
      &:first-child{
        width: 320px;
      }
      .el-input__inner{
        height: 44px;
        text-align: center;
        font-size:16px;
        border-radius: 2px!important;
        &::placeholder{
          font-size:14px;
        }
      }
      span{
        position: absolute;
        z-index:2;
        top: -22px;
        left:50%;
        margin-left: -14px;
        color:#7e8e9f;
      }
    }
    .link_panel{
      margin-right: 20px;
      color:#00b4ff;
    }
    .btn_panel{
      width: 180px;
      height: 44px!important;
      border-radius: 2px!important;
      justify-content: center!important;
      padding: 0!important;
      margin-right: 20px;
    }
    .el-form-item.is-success .el-input__inner{
      border-color:#dcdfe6!important;
    }
  }
  .serial_number_list{
    display: flex;
    align-items: center;
    color:#333;
    .list_panel{
      background-color: #f5f5f5;
      height: 350px;
      margin-top: 30px;
      border:@mesBorDefault;
      position: relative;
      &::after{
        content: '';
        display: block;
        position: absolute;
        border-right: @mesBorDefault;
        top: 44px;
        right: 14px;
        height:calc(100% - 44px);
      }
      .empty_panel{
        width: 100%;
        height: calc(100% - 44px);
        display: flex;
        align-items: center;
        justify-content: center;
        color: #a1b1c1;
      }
      .list_container{
        &::-webkit-scrollbar {
          /*滚动条*/
          width: 14px;
          height: 14px;
          cursor: pointer;
          margin-left: 4px;
        }
        &::-webkit-scrollbar-thumb {
          /*小方块*/
          border-radius: 16px;
          box-shadow: @mesTableScrollThumbShow;
          background: @mesTableScrollThumbBg;
          cursor: pointer;
          border: 3px solid #f5f5f5;
        }
        &::-webkit-scrollbar-thumb:hover {
          cursor: pointer;
        }
        &::-webkit-scrollbar-track {
          /*轨道*/
          width: 14px;
          background: #f5f5f5;
        }
        &::-webkit-scrollbar-track:hover {
          cursor: pointer;
        }
      }
    }
  }
</style>
